import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue')
  },
  {
    path: '/environments',
    name: 'Environments',
    component: () => import('../views/Environments.vue')
  },
  {
    path: '/testcases',
    name: 'TestCases',
    component: () => import('../views/TestCases.vue')
  },
  {
    path: '/executions',
    name: 'Executions',
    component: () => import('../views/Executions.vue')
  },
  {
    path: '/reports',
    name: 'Reports',
    component: () => import('../views/Reports.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/daily/log',
    name: 'DailyLog',
    component: () => import('../views/Daily/DailyLog.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('access')
  const isLoginPage = to.path === '/login' || to.path === '/register'
  
  if (!token && !isLoginPage) {
    // 没有token且不是登录/注册页面，跳转到登录页
    next('/login')
  } else if (token && isLoginPage) {
    // 有token但访问登录/注册页面，跳转到仪表盘
    next('/dashboard')
  } else {
    next()
  }
})

export default router 